/**
 * halrfi.c
 *
 * hardware abstraction layer radio frequency interface.
 *
 * Copyright (c) sti-seedclass 2011, tankery.chen@gmail.com
 */
#include "LPC11xx.h"
#include "halrfi.h"
#include "uart.h"
#include "gpio.h"
#include "string.h"

static callback_void dataReceivedFunc;
static volatile uint32_t rdyBufSize;
extern volatile uint32_t UARTCount;
extern volatile uint8_t UARTBuffer[BUFSIZE];

void dataReceived(void* null)
{
    if (dataReceivedFunc != 0) {
        dataReceivedFunc(0);
    }
}

void halrfiInit(void)
{
    UARTInit(BANDRATE);
    UARTSetIntCallback(dataReceived);
    halrfiTxOff();
    halrfiRxOn();
    dataReceivedFunc = 0;
	rdyBufSize = 1;
    
    // this pin control the receive enable.
    GPIOSetDir(0, 8, GPIO_DIR_OUTPUT);
}

void halrfiTxOn()
{
    // close receive first.
    halrfiRxOff();
    
    LPC_IOCON->PIO1_7 &= ~0x07;
    LPC_IOCON->PIO1_7 |= 0x01;      // set as UART TXD.
    
    
    /* Enable the UART Interrupt */
    NVIC_EnableIRQ(UART_IRQn);
}

void halrfiRxOn()
{
    // close transform first.
    halrfiTxOff();
    
    // enable receive.
    GPIOSetValue(0, 8, 1);
	LPC_UART->IER = IER_THRE | IER_RLS | IER_RBR;	/* Re-enable RBR */
    
    /* Enable the UART Interrupt */
    NVIC_EnableIRQ(UART_IRQn);
}

void halrfiTxOff()
{
    NVIC_DisableIRQ(UART_IRQn);
    LPC_IOCON->PIO1_7 &= ~0x07;     // set as normal pin.
    GPIOSetDir(1, 7, GPIO_DIR_OUTPUT);
    GPIOSetValue(1, 7, 0);          // set low to close RF.
}

void halrfiRxOff()
{
    // Disable RBR
	LPC_UART->IER = IER_THRE | IER_RLS;
    // close receive.
    GPIOSetValue(0, 8, 0);
}

void halrfiSetIntCallback(callback_void func)
{
    dataReceivedFunc = func;
}

void halrfiSend(uint8_t * data, uint32_t length)
{
	halrfiTxOn();
    UARTSend(data, length);
}

void halrfiSetRdySize(uint32_t len)
{
	rdyBufSize = len;
}

uint32_t halrfiDataRdy(void)
{
    return (UARTCount >= rdyBufSize);
}

uint32_t halrfiReceive(uint8_t *data)
{
    uint32_t count = UARTCount;
    memcpy (data, (uint8_t*)UARTBuffer, UARTCount);

    UARTCount = 0;
    
    return count;
}

